//
//  SKLoginVController.m
//  aURobot
//
//  Created by cdong on 16/2/17.
//  Copyright © 2016年 cdong. All rights reserved.
//

#import "SKLoginVController.h"
#import "SKLoginView.h"
#import "SKRegisterVController.h"
#import "SKFirstVController.h"
#import "AFHTTPSessionManager.h"

#import "growthPhotosVController.h"

@interface SKLoginVController ()<UITextFieldDelegate>

@property (nonatomic ,strong)SKLoginView *loginView;
@property (nonatomic ,assign)NSInteger pwdShiftFlag;

@end

@implementation SKLoginVController

- (void)loadView{
    self.loginView = [[SKLoginView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.view = self.loginView;
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    [self.loginView.loginBtn addTarget:self action:@selector(loginBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.loginView.registerBtn addTarget:self action:@selector(registerBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.loginView.retrievePwdBtn addTarget:self action:@selector(retrievePwdBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.pwdShiftFlag = 0;
    [self.loginView.pawBtn addTarget:self action:@selector(pwdShiftBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged) name:UITextFieldTextDidChangeNotification object:self.loginView.userNameTF];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged) name:UITextFieldTextDidChangeNotification object:self.loginView.pawTF];
    self.loginView.userNameTF.delegate = self;
    self.loginView.pawTF.delegate = self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *userName = [userDefaults objectForKey:@"userName"];
    NSString *pwd = [userDefaults objectForKey:@"password"];
    self.loginView.userNameTF.text = userName;
    self.loginView.pawTF.text = pwd;
    if (![self.loginView.userNameTF.text isEqualToString:@""] && ![self.loginView.pawTF.text isEqualToString:@""]) {
        self.loginView.loginBtn.userInteractionEnabled = YES;
        [self.loginView.loginBtn setTitleColor:[RGBColorEncapsulation colorWithRGB:0xffffff alpha:1] forState:UIControlStateNormal];
    }
}

// 输入框文字判断
- (void)textFieldChanged{
    if (![self.loginView.userNameTF.text isEqualToString:@""] && ![self.loginView.pawTF.text isEqualToString:@""]) {
        self.loginView.loginBtn.userInteractionEnabled = YES;
        [self.loginView.loginBtn setTitleColor:[RGBColorEncapsulation colorWithRGB:0xffffff alpha:1] forState:UIControlStateNormal];
    }else{
        self.loginView.loginBtn.userInteractionEnabled = NO;
        [self.loginView.loginBtn setTitleColor:[RGBColorEncapsulation colorWithRGB:0xffffff alpha:.5] forState:UIControlStateNormal];
    }
}

#pragma 调试接口
// 切换密文／明文
- (void)pwdShiftBtnAction:(UIButton *)sender{
    
    growthPhotosVController *first = [[growthPhotosVController alloc]init];
    [self.navigationController pushViewController:first animated:YES];
    
//    if (self.pwdShiftFlag == 1) {
//        self.loginView.pawTF.secureTextEntry = YES;
//        [self.loginView.pawBtn setBackgroundImage:[UIImage imageNamed:@"icon_eye"] forState:UIControlStateNormal];
//        self.pwdShiftFlag = 0;
//    }else{
//        self.loginView.pawTF.secureTextEntry = NO;
//        [self.loginView.pawBtn setBackgroundImage:[UIImage imageNamed:@"icon_eye_red"] forState:UIControlStateNormal];
//        self.pwdShiftFlag = 1;
//    }
}

int codeRR = 0;

// 登录
- (void)loginBtnAction:(UIButton *)sender{
    if ([self.loginView.userNameTF.text isEqualToString:@""]) {
        [self alertReminderMessage:@"用户名不能为空"];
        return;
    }
    
    if ([self.loginView.pawTF.text isEqualToString:@""]) {
        [self alertReminderMessage:@"密码不能为空"];
        return;
    }
    
    NSString *urlStr =  [NSString stringWithFormat:@"http://api.au-smart.cn/index.php?act=login&userName=%@&password=%@",self.loginView.userNameTF.text,self.loginView.pawTF.text];
    NSString *utf = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:utf parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        NSNumber *error = [responseObject objectForKey:@"error"];
        NSNumber *uid = [responseObject objectForKey:@"uid"];
        NSNumber *errorCode = [responseObject objectForKey:@"errorCode"];
        NSString *sesskey = [responseObject objectForKey:@"sesskey"];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:uid forKey:@"uid"];
        [defaults setObject:sesskey forKey:@"sesskey"];
        if (error.integerValue == 0) {
            NSUserDefaults *userdefaut = [NSUserDefaults standardUserDefaults];
            [userdefaut setObject:self.loginView.userNameTF.text forKey:@"userName"];
            [userdefaut setObject:self.loginView.pawTF.text forKey:@"password"];
            if (errorCode.integerValue == 1031) { // 老用户未绑定手机号跳转
                codeRR = 103;
                [userdefaut setInteger:codeRR forKey:@"registerOrGetCode"];
                SKRegisterVController *bandPhoneV = [[SKRegisterVController alloc]init];
                [self.navigationController pushViewController:bandPhoneV animated:YES];
            }else{
                SKFirstVController *ss = [[SKFirstVController alloc]init];
                ss.updateUIFlag = YES;
                [self.navigationController pushViewController:ss animated:YES];
            }
        }else{
            if (errorCode.integerValue == 1010) {
                [self alertReminderMessage:@"用户名或手机号错误,请重新填写"];
            }else if (errorCode.integerValue == 1011){
                [self alertReminderMessageSpecial:@"密码错误,找回密码?"];
            }else{
                [self alertReminderMessage:@"用户名或密码错误"];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"fail~~~");
    }];
}

// 注册
- (void)registerBtnAction:(UIButton *)sender{
    codeRR = 101;
    SKRegisterVController *registerVC = [[SKRegisterVController alloc]init];
    NSUserDefaults *userdefaut = [NSUserDefaults standardUserDefaults];
    [userdefaut setInteger:codeRR forKey:@"registerOrGetCode"];
    [self.navigationController pushViewController:registerVC animated:YES];
}

// 忘记密码
- (void)retrievePwdBtnAction:(UIButton *)sender{
    codeRR = 102;
    SKRegisterVController *registerVC = [[SKRegisterVController alloc]init];
    NSUserDefaults *userdefaut = [NSUserDefaults standardUserDefaults];
    [userdefaut setInteger:codeRR forKey:@"registerOrGetCode"];
    [self.navigationController pushViewController:registerVC animated:YES];
}

// 点击return回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

// 点击空白回收键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.loginView.userNameTF resignFirstResponder];
    [self.loginView.pawTF resignFirstResponder];
}

// 提示弹框
- (void)alertReminderMessage:(NSString *)message
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

// 提示弹框
- (void)alertReminderMessageSpecial:(NSString *)message
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"找回密码" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        codeRR = 102;
        SKRegisterVController *registerVC = [[SKRegisterVController alloc]init];
        NSUserDefaults *userdefaut = [NSUserDefaults standardUserDefaults];
        [userdefaut setInteger:codeRR forKey:@"registerOrGetCode"];
        [self.navigationController pushViewController:registerVC animated:YES];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
